<template>
    <div class="app-container">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span>推广返利管理</span>
                </div>
            </template>

            <!-- 搜索区域 -->
            <div class="search-container">
                <el-form :model="searchForm" :inline="true" class="search-form">
                    <el-form-item label="用户邮箱">
                        <el-input
                            v-model="searchForm.email"
                            placeholder="请输入用户邮箱"
                            clearable
                            style="width: 200px"
                        />
                    </el-form-item>
                    <el-form-item label="推广码">
                        <el-input
                            v-model="searchForm.affiliate_code"
                            placeholder="请输入推广码"
                            clearable
                            style="width: 200px"
                        />
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-select
                            v-model="searchForm.status"
                            placeholder="请选择状态"
                            clearable
                            style="width: 120px"
                        >
                            <el-option label="启用" value="1" />
                            <el-option label="禁用" value="0" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">
                            <el-icon><Search /></el-icon>
                            搜索
                        </el-button>
                        <el-button @click="handleReset">
                            <el-icon><Refresh /></el-icon>
                            重置
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 表格区域 -->
            <el-table
                v-loading="loading"
                :data="tableData"
                border
                stripe
                style="width: 100%"
            >
                <el-table-column prop="user_id" label="用户ID" width="80" />
                <el-table-column
                    prop="email"
                    label="用户邮箱"
                    width="180"
                    show-overflow-tooltip
                />
                <el-table-column
                    prop="affiliate_code"
                    label="推广码"
                    width="120"
                />
                <el-table-column
                    prop="commission_rate"
                    label="返利比例"
                    width="90"
                >
                    <template #default="{ row }">
                        {{ row.commission_rate }}%
                    </template>
                </el-table-column>
                <el-table-column
                    prop="total_commission"
                    label="累计返利"
                    width="100"
                >
                    <template #default="{ row }">
                        ¥{{ row.total_commission }}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="total_invitees"
                    label="邀请人数"
                    width="90"
                />
                <el-table-column
                    prop="total_orders"
                    label="订单数"
                    width="80"
                />
                <el-table-column
                    prop="pending_commission"
                    label="待结算返利"
                    width="100"
                >
                    <template #default="{ row }">
                        <span style="color: #e6a23c"
                            >¥{{ row.pending_commission }}</span
                        >
                    </template>
                </el-table-column>
                <el-table-column
                    prop="settled_commission"
                    label="已结算返利"
                    width="100"
                >
                    <template #default="{ row }">
                        <span style="color: #67c23a"
                            >¥{{ row.settled_commission }}</span
                        >
                    </template>
                </el-table-column>
                <el-table-column
                    prop="ali_pay_account"
                    label="支付宝账号"
                    width="150"
                    show-overflow-tooltip
                >
                    <template #default="{ row }">
                        <span v-if="row.ali_pay_account">{{
                            row.ali_pay_account
                        }}</span>
                        <span v-else style="color: #999">未设置</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="ali_pay_name"
                    label="支付宝姓名"
                    width="120"
                    show-overflow-tooltip
                >
                    <template #default="{ row }">
                        <span v-if="row.ali_pay_name">{{
                            row.ali_pay_name
                        }}</span>
                        <span v-else style="color: #999">未设置</span>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="70">
                    <template #default="{ row }">
                        <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                            {{ row.status === 1 ? '启用' : '禁用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="create_time"
                    label="创建时间"
                    width="150"
                >
                    <template #default="{ row }">
                        {{ row.create_time.split('T')[0] }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" fixed="right">
                    <template #default="{ row }">
                        <el-button
                            type="primary"
                            size="small"
                            @click="handleViewDetails(row)"
                        >
                            <el-icon><View /></el-icon>
                            查看详情
                        </el-button>
                        <el-button
                            :type="row.status === 1 ? 'warning' : 'success'"
                            size="small"
                            @click="handleToggleStatus(row)"
                        >
                            {{ row.status === 1 ? '禁用' : '启用' }}
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination
                    v-model:current-page="pagination.current"
                    v-model:page-size="pagination.size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="pagination.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </el-card>

        <!-- 详情对话框 -->
        <el-dialog
            v-model="detailDialogVisible"
            title="推广详情"
            width="80%"
            :close-on-click-modal="false"
        >
            <div v-if="currentUserDetail">
                <!-- 基本信息 -->
                <el-card class="detail-card" style="margin-bottom: 20px">
                    <template #header>
                        <span>基本信息</span>
                        <el-button
                            type="primary"
                            size="small"
                            style="float: right"
                            @click="showEditAliPayDialog = true"
                        >
                            <el-icon><Edit /></el-icon>
                            编辑支付宝信息
                        </el-button>
                    </template>
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <div class="detail-item">
                                <label>用户邮箱：</label>
                                <span>{{ currentUserDetail.email }}</span>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="detail-item">
                                <label>推广码：</label>
                                <span>{{
                                    currentUserDetail.affiliate_code
                                }}</span>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="detail-item">
                                <label>返利比例：</label>
                                <span
                                    >{{
                                        currentUserDetail.commission_rate
                                    }}%</span
                                >
                            </div>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20" style="margin-top: 15px">
                        <el-col :span="12">
                            <div class="detail-item">
                                <label>支付宝账号：</label>
                                <span
                                    v-if="currentUserDetail.ali_pay_account"
                                    >{{
                                        currentUserDetail.ali_pay_account
                                    }}</span
                                >
                                <span v-else style="color: #999">未设置</span>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="detail-item">
                                <label>支付宝姓名：</label>
                                <span v-if="currentUserDetail.ali_pay_name">{{
                                    currentUserDetail.ali_pay_name
                                }}</span>
                                <span v-else style="color: #999">未设置</span>
                            </div>
                        </el-col>
                    </el-row>
                </el-card>

                <!-- 统计信息 -->
                <el-card class="detail-card" style="margin-bottom: 20px">
                    <template #header>
                        <span>统计信息</span>
                    </template>
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <div class="stat-item">
                                <div class="stat-value">
                                    {{ inviteStats.total_invitees }}
                                </div>
                                <div class="stat-label">邀请人数</div>
                            </div>
                        </el-col>
                        <el-col :span="6">
                            <div class="stat-item">
                                <div class="stat-value">
                                    {{ inviteStats.total_orders }}
                                </div>
                                <div class="stat-label">订单数</div>
                            </div>
                        </el-col>
                        <el-col :span="6">
                            <div class="stat-item">
                                <div class="stat-value">
                                    ¥{{ inviteStats.total_order_amount }}
                                </div>
                                <div class="stat-label">订单金额</div>
                            </div>
                        </el-col>
                        <el-col :span="6">
                            <div class="stat-item">
                                <div class="stat-value">
                                    ¥{{ inviteStats.total_commission }}
                                </div>
                                <div class="stat-label">累计返利</div>
                            </div>
                        </el-col>
                    </el-row>
                </el-card>

                <!-- 返利状态统计 -->
                <el-card class="detail-card" style="margin-bottom: 20px">
                    <template #header>
                        <span>返利状态统计</span>
                    </template>
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <div class="stat-item">
                                <div class="stat-value pending">
                                    ¥{{ inviteStats.pending_commission }}
                                </div>
                                <div class="stat-label">待结算</div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="stat-item">
                                <div class="stat-value settled">
                                    ¥{{ inviteStats.settled_commission }}
                                </div>
                                <div class="stat-label">已结算</div>
                            </div>
                        </el-col>
                        <el-col :span="8">
                            <div class="stat-item">
                                <el-button
                                    type="primary"
                                    @click="handleSettleAll"
                                >
                                    <el-icon><Money /></el-icon>
                                    一键结算待结算返利
                                </el-button>
                            </div>
                        </el-col>
                    </el-row>
                </el-card>

                <!-- 被邀请人列表 -->
                <el-card class="detail-card" style="margin-bottom: 20px">
                    <template #header>
                        <span>被邀请人列表</span>
                    </template>
                    <el-table :data="inviteeList" border stripe>
                        <el-table-column
                            prop="email"
                            label="邮箱"
                            width="160"
                        />
                        <el-table-column
                            prop="register_time"
                            label="注册时间"
                            width="160"
                        >
                            <template #default="{ row }">
                                {{ row.register_time.split('T')[0] }}
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="total_orders"
                            label="订单数"
                            width="100"
                        />
                        <el-table-column
                            prop="total_order_amount"
                            label="订单金额"
                            width="120"
                        >
                            <template #default="{ row }">
                                ¥{{ row.total_order_amount }}
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="total_commission"
                            label="返利金额"
                            width="120"
                        >
                            <template #default="{ row }">
                                ¥{{ row.total_commission }}
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="last_order_time"
                            label="最后订单时间"
                            width="160"
                        >
                            <template #default="{ row }">
                                {{ row.last_order_time.split('T')[0] }}
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>

                <!-- 返利记录 -->
                <el-card class="detail-card">
                    <template #header>
                        <span>返利记录</span>
                    </template>
                    <el-table :data="commissionList" border stripe>
                        <el-table-column
                            prop="invitee_email"
                            label="被邀请人邮箱"
                            width="160"
                        />
                        <el-table-column
                            prop="order_no"
                            label="订单号"
                            width="190"
                        />
                        <el-table-column
                            prop="order_amount"
                            label="订单金额"
                            width="120"
                        >
                            <template #default="{ row }">
                                ¥{{ row.order_amount }}
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="commission_rate"
                            label="返利比例"
                            width="100"
                        >
                            <template #default="{ row }">
                                {{ row.commission_rate }}%
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="commission_amount"
                            label="返利金额"
                            width="120"
                        >
                            <template #default="{ row }">
                                ¥{{ row.commission_amount }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="状态" width="100">
                            <template #default="{ row }">
                                <el-tag :type="getStatusType(row.status)">
                                    {{ getStatusText(row.status) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="settle_time"
                            label="结算时间"
                            width="160"
                        >
                            <template #default="{ row }">
                                {{
                                    row.settle_time
                                        ? row.settle_time.split('T')[0]
                                        : ''
                                }}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="160">
                            <template #default="{ row }">
                                <el-button
                                    v-if="row.status === 0"
                                    type="success"
                                    size="small"
                                    @click="handleSettle(row)"
                                >
                                    结算
                                </el-button>
                                <el-button
                                    v-if="row.status === 0"
                                    type="danger"
                                    size="small"
                                    @click="handleCancel(row)"
                                >
                                    取消
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </div>
        </el-dialog>

        <!-- 编辑支付宝信息对话框 -->
        <el-dialog
            v-model="showEditAliPayDialog"
            title="编辑支付宝信息"
            width="500px"
            :close-on-click-modal="false"
        >
            <el-form :model="aliPayForm" label-width="120px">
                <el-form-item label="支付宝账号">
                    <el-input
                        v-model="aliPayForm.ali_pay_account"
                        placeholder="请输入支付宝账号"
                        clearable
                    />
                </el-form-item>
                <el-form-item label="支付宝姓名">
                    <el-input
                        v-model="aliPayForm.ali_pay_name"
                        placeholder="请输入支付宝真实姓名"
                        clearable
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showEditAliPayDialog = false"
                        >取消</el-button
                    >
                    <el-button type="primary" @click="handleUpdateAliPayInfo"
                        >确定</el-button
                    >
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, View, Money, Edit } from '@element-plus/icons-vue'
import {
    getAffiliateList,
    getAffiliateDetail,
    updateAffiliateStatus,
    settleCommission,
    cancelCommission,
    batchSettleCommission,
    updateAliPayInfo
} from '@/api/bg/affiliate'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const detailDialogVisible = ref(false)
const currentUserDetail = ref(null)
const inviteStats = ref(null)
const inviteeList = ref([])
const commissionList = ref([])
const showEditAliPayDialog = ref(false)
const aliPayForm = reactive({
    ali_pay_account: '',
    ali_pay_name: ''
})

// 搜索表单
const searchForm = reactive({
    email: '',
    affiliate_code: '',
    status: ''
})

// 分页
const pagination = reactive({
    current: 1,
    size: 20,
    total: 0
})

// 获取列表数据
const loadData = async () => {
    loading.value = true
    try {
        const params = {
            page: pagination.current,
            size: pagination.size,
            ...searchForm
        }
        const response = await getAffiliateList(params)
        tableData.value = response.data.records || []
        pagination.total = response.data.total || 0
    } catch (error) {
        ElMessage.error('获取数据失败')
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    pagination.current = 1
    loadData()
}

// 重置
const handleReset = () => {
    Object.keys(searchForm).forEach((key) => {
        searchForm[key] = ''
    })
    pagination.current = 1
    loadData()
}

// 分页处理
const handleSizeChange = (size) => {
    pagination.size = size
    pagination.current = 1
    loadData()
}

const handleCurrentChange = (current) => {
    pagination.current = current
    loadData()
}

// 查看详情
const handleViewDetails = async (row) => {
    try {
        const response = await getAffiliateDetail(row.user_id)
        currentUserDetail.value = row
        inviteStats.value = response.data.stats
        inviteeList.value = response.data.invitee_list || []
        commissionList.value = response.data.commission_list || []

        // 预填充支付宝信息到编辑表单
        aliPayForm.ali_pay_account = row.ali_pay_account || ''
        aliPayForm.ali_pay_name = row.ali_pay_name || ''

        detailDialogVisible.value = true
    } catch (error) {
        ElMessage.error('获取详情失败')
    }
}

// 切换状态
const handleToggleStatus = async (row) => {
    const action = row.status === 1 ? '禁用' : '启用'
    try {
        await ElMessageBox.confirm(
            `确定要${action}该用户的推广功能吗？`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        await updateAffiliateStatus(row.user_id, row.status === 1 ? 0 : 1)
        ElMessage.success(`${action}成功`)
        loadData()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error(`${action}失败`)
        }
    }
}

// 结算返利
const handleSettle = async (row) => {
    try {
        await ElMessageBox.confirm('确定要结算这笔返利吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await settleCommission(row.id)
        ElMessage.success('结算成功')
        handleViewDetails(currentUserDetail.value)
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('结算失败')
        }
    }
}

// 取消返利
const handleCancel = async (row) => {
    try {
        await ElMessageBox.confirm('确定要取消这笔返利吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        await cancelCommission(row.id)
        ElMessage.success('取消成功')
        handleViewDetails(currentUserDetail.value)
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('取消失败')
        }
    }
}

// 一键结算
const handleSettleAll = async () => {
    try {
        await ElMessageBox.confirm('确定要结算所有待结算返利吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        // 这里需要调用批量结算接口

        await batchSettleCommission(currentUserDetail.value.user_id)
        ElMessage.success('批量结算成功')
        handleViewDetails(currentUserDetail.value)
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('批量结算失败')
        }
    }
}

// 获取状态类型
const getStatusType = (status) => {
    const types = {
        0: 'warning', // 待结算
        1: 'success', // 已结算
        2: 'danger' // 已取消
    }
    return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
    const texts = {
        0: '待结算',
        1: '已结算',
        2: '已取消'
    }
    return texts[status] || '未知'
}

// 更新支付宝信息
const handleUpdateAliPayInfo = async () => {
    try {
        await updateAliPayInfo(currentUserDetail.value.user_id, {
            ali_pay_account: aliPayForm.ali_pay_account,
            ali_pay_name: aliPayForm.ali_pay_name
        })
        ElMessage.success('支付宝信息更新成功')
        showEditAliPayDialog.value = false

        // 更新当前用户详情中的支付宝信息
        currentUserDetail.value.ali_pay_account = aliPayForm.ali_pay_account
        currentUserDetail.value.ali_pay_name = aliPayForm.ali_pay_name

        // 刷新列表数据
        loadData()
    } catch (error) {
        ElMessage.error('支付宝信息更新失败')
    }
}

// 初始化
onMounted(() => {
    loadData()
})
</script>

<style scoped>
.app-container {
    padding: 20px;
}

.search-container {
    margin-bottom: 20px;
}

.search-form {
    background: #f5f5f5;
    padding: 20px;
    border-radius: 4px;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}

.detail-card {
    margin-bottom: 20px;
}

.detail-item {
    margin-bottom: 10px;
}

.detail-item label {
    font-weight: bold;
    margin-right: 10px;
}

.stat-item {
    text-align: center;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 8px;
}

.stat-value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 5px;
}

.stat-value.pending {
    color: #e6a23c;
}

.stat-value.settled {
    color: #67c23a;
}

.stat-label {
    color: #666;
    font-size: 14px;
}
</style>
